import 'dart:math';
import 'package:flutter/material.dart';

class GradientProgressIndicator extends StatefulWidget {
  final double progress;

  const GradientProgressIndicator({super.key, required this.progress});

  @override
  State<GradientProgressIndicator> createState() =>
      _GradientProgressIndicatorState();
}

class _GradientProgressIndicatorState
    extends State<GradientProgressIndicator> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 100,
      width: 100,
      child: CustomPaint(
        painter: _ProgressPainter(progress: widget.progress),
      ),
    );
  }
}

class _ProgressPainter extends CustomPainter {
  final double progress;

  _ProgressPainter({required this.progress});

  @override
  void paint(Canvas canvas, Size size) {
    final centerX = size.width / 2;
    final centerY = size.height / 2;
    final radius = size.width / 2;

    // 绘制背景圆环（单色 f5f5f5）
    final backgroundPaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 8
      ..color = const Color(0xfff5f5f5);

    canvas.drawCircle(Offset(centerX, centerY), radius, backgroundPaint);

    // 绘制进度圆环（渐变色）
    final progressPaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 8
      ..shader = LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [
          Color(0xffF3FF47),
          Color(0xff95FFB1),
          Color(0xff9ED7FF),
          Color(0xffE046FF),
        ],
      ).createShader(Rect.fromCircle(center: Offset(centerX, centerY), radius: radius));

    final progressAngle = 2 * pi * progress;
    canvas.drawArc(Rect.fromCircle(center: Offset(centerX, centerY), radius: radius), -pi / 2, progressAngle, false, progressPaint);

    // 绘制进度百分比文本
    final textStyle = TextStyle(fontSize: 28, color: Colors.black,fontWeight: FontWeight.bold);
    final textSpan = TextSpan(text: '${(progress * 100).toInt()}%', style: textStyle);
    final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr);
    textPainter.layout();
    final textWidth = textPainter.width;
    final textHeight = textPainter.height;
    textPainter.paint(canvas, Offset(centerX - textWidth / 2, centerY - textHeight / 2));
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}